package com.ifast.common.utils.qukan;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.collections.MapUtils;
import org.json.JSONObject;

import com.google.common.collect.Maps;
import com.google.gson.GsonBuilder;
import com.ifast.common.utils.qukan.auth.ServiceSignature;
import com.ifast.common.utils.qukan.entity.ApiResult;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 
 * @author ShiQiang
 *
 */
public class QuKanApiUtils{
	
	//http请求框架
	private static Retrofit retrofit = new Retrofit.Builder().baseUrl(HttpCommon.url)
			.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
			.client(new OkHttpClient.Builder()
					.connectTimeout(50000, TimeUnit.SECONDS)
					.readTimeout(5000, TimeUnit.SECONDS)
					.addInterceptor(new CommonInterceptor())
					.writeTimeout(5000, TimeUnit.SECONDS) 
					.build()) 
			.build();
	
	
	public static ApiResult getInfo(String videoId){
		QuKanApi  apiService = retrofit.create(QuKanApi.class); 
		Map<String,String> map = Maps.newHashMap();
		map.put("videoId", videoId);
		try {
			Response<ApiResult> response = apiService.getInfo(buildParameter(map)).execute();
			return response.body();
		} catch (IOException e) {
			return null;
		}
	}
	
	public static ApiResult list(){
		QuKanApi  apiService = retrofit.create(QuKanApi.class);  
		try {
			Response<ApiResult> response = apiService.list(buildParameter()).execute();
			return response.body();
		} catch (IOException e) {
			return null;
		}
	}
	
	public static void main(String[] args) throws IOException { 
		System.out.println(list().toString()); 
	}
	 
	
	private static RequestBody buildParameter(){
		return buildParameter(null);
	}
	
	private static RequestBody buildParameter(Map<String,String> param){
		
		String nonce = String.valueOf(System.currentTimeMillis());
		
        String signature = ServiceSignature.create()
        		.computeSignature(HttpCommon.appSecret, 
        				new StringBuilder().append("appKey=")
        					.append(HttpCommon.appKey)
        					.append("&nonce=").append(nonce).toString());
        
        JSONObject json = new JSONObject();
	 	json.put("appKey", HttpCommon.appKey).put("nonce", nonce).put("signature", signature);
	 	if(MapUtils.isNotEmpty(param)){
	 		param.forEach((key,value) ->{
	 			json.put(key, value);
	 		});
	 	} 
	 	
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json.toString());
	}
}
